package org.glz.config.etc;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Resource
    private DbRealm dbRealm;

    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
//        webSecurityManager.setSessionManager(new DefaultSessionManager());
        webSecurityManager.setRealm(dbRealm);
        return webSecurityManager;
    }

   /* @PostConstruct//spring容器初始化完之后会执行
    public void init(){
        SecurityUtils.setSecurityManager(securityManager());
    }*/


    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean filterFactoryBean(){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager());
        Map<String,String> chainDefinition = new LinkedHashMap<>();
        chainDefinition.put("/bb/login","anon");
        chainDefinition.put("/webjars/**","anon");
        chainDefinition.put("/static/**","anon");
        chainDefinition.put("/logout","logout");
        chainDefinition.put("/**","authc");
        filterFactoryBean.setFilterChainDefinitionMap(chainDefinition);
        filterFactoryBean.setLoginUrl("/bb/login");
        return filterFactoryBean;
    }

    /*@Bean
    //springboot中起作用，ssm项目不生效
    public ShiroFilterChainDefinition chainDefinition(){
        DefaultShiroFilterChainDefinition filterChainDefinition = new DefaultShiroFilterChainDefinition();
        filterChainDefinition.addPathDefinition("/bb/login","anon");
        filterChainDefinition.addPathDefinition("/webjars/**","anon");
        filterChainDefinition.addPathDefinition("/static/**","anon");
        filterChainDefinition.addPathDefinition("/logout","logout");
        filterChainDefinition.addPathDefinition("/**","authc");
        return filterChainDefinition;
    }*/


}
